package systempen.cmanager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import systempen.cmanager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


/**
 * @author Ashwin Kumar
 *
 */
public class ManageData extends AcitivityLowImportance {

	//private MyApplication application;

	private Button exportDbToSdButton;
	private Button importDbFromSdButton;
	private Button exportDbXmlToSdButton;
	private Button _exportDataAsCSVButton;
	public Context c;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ThemePicker.onActivityCreateSetTheme(this);
		//this.application = (MyApplication) this.getApplication();

		this.setContentView(R.layout.managedata);
		c = this;
		this.exportDbToSdButton = (Button) this
				.findViewById(R.id.exportdbtosdbutton);
		this.exportDbToSdButton.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				if (ManageData.this.isExternalStorageAvail()) {
					new ExportDatabaseFileTask().execute();
				} else {
					Toast.makeText(ManageData.this,"External storage is not available, unable to export data.",Toast.LENGTH_SHORT).show();
				}
			}
		});
		this.importDbFromSdButton = (Button) this
				.findViewById(R.id.importdbtosdbutton);
		this.importDbFromSdButton.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				if (ManageData.this.isExternalStorageAvail()) {
					//TODO dodati r u sure?
					///////////////////////////////////////
					DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
					    @Override
					    public void onClick(DialogInterface dialog, int which) {
					        switch (which){
					        case DialogInterface.BUTTON_POSITIVE:
					            //Yes button clicked
					        	new ImportDatabaseFileTask().execute();
					            break;

					        case DialogInterface.BUTTON_NEGATIVE:
					            //No button clicked
					            break;
					        }
					    }
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(c);
					builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
					    .setNegativeButton("No", dialogClickListener).show();
					///////////////////////////////////////
				} else {
					Toast.makeText(ManageData.this,"External storage is not available, unable to export data.",Toast.LENGTH_SHORT).show();
				}
			}
		});

		this.exportDbXmlToSdButton = (Button) this
				.findViewById(R.id.exportdbxmltosdbutton);
		this.exportDbXmlToSdButton.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				if (ManageData.this.isExternalStorageAvail()) {
					new ExportDataAsXmlTask().execute("CostManager",
							"CostManager");
				} else {
					Toast.makeText(
							ManageData.this,
							"External storage is not available, unable to export data.",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		this._exportDataAsCSVButton = (Button) this.findViewById(R.id.exportdbCSVtosdbutton);
		this._exportDataAsCSVButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(final View v) {
				// TODO Auto-generated method stub
				if (ManageData.this.isExternalStorageAvail()){
					new ExportDataAsCSVTask().execute("CostManager.csv","CostManager");
				} else {
					Toast.makeText(
							ManageData.this,
							"External storage is not available, unable to export data.",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestoreInstanceState(final Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(final Bundle saveState) {
		super.onSaveInstanceState(saveState);
	}

	public boolean isExternalStorageAvail() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
		private final ProgressDialog dialog = new ProgressDialog(ManageData.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Exporting database...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Boolean doInBackground(final String... args) {

			File dbFile = getApplicationContext().getDatabasePath("DBS");

			File exportDir = new File(
					Environment.getExternalStorageDirectory(), "CostManager");
			if (!exportDir.exists()) {
				exportDir.mkdirs();
			}
			File file = new File(exportDir, dbFile.getName());

			try {
				file.createNewFile();
				this.copyFile(dbFile, file);
				return true;
			} catch (IOException e) {
				Log.e("CMANAGER", e.getMessage(), e);
				return false;
			}
		}

		// can use UI thread here
		protected void onPostExecute(final Boolean success) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			if (success) {
				Toast.makeText(ManageData.this, "Export successful!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ManageData.this, "Export failed",
						Toast.LENGTH_SHORT).show();
			}
		}

		void copyFile(File src, File dst) throws IOException {
			FileChannel inChannel = new FileInputStream(src).getChannel();
			FileChannel outChannel = new FileOutputStream(dst).getChannel();
			try {
				inChannel.transferTo(0, inChannel.size(), outChannel);
			} finally {
				if (inChannel != null)
					inChannel.close();
				if (outChannel != null)
					outChannel.close();
			}
		}

	}
//------------------------------------------------------------
	public class ImportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
		private final ProgressDialog dialog = new ProgressDialog(ManageData.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Importing database...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Boolean doInBackground(final String... args) {

			File dbFile = getApplicationContext().getDatabasePath("DBS");

			File exportDir = new File(Environment.getExternalStorageDirectory(), "CostManager");
			if (!exportDir.exists()) {
				exportDir.mkdirs();
			}
			File file = new File(exportDir, dbFile.getName());

			try {
				file.createNewFile();
				//this.copyFile(dbFile, file);
				this.copyFile(file,dbFile);
				return true;
			} catch (IOException e) {
				Log.e("CMANAGER", e.getMessage(), e);
				return false;
			}
		}

		// can use UI thread here
		protected void onPostExecute(final Boolean success) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			if (success) {
				Toast.makeText(ManageData.this, "Import successful!",Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ManageData.this, "Import failed",Toast.LENGTH_SHORT).show();
			}
		}

		void copyFile(File src, File dst) throws IOException {
			FileChannel inChannel = new FileInputStream(src).getChannel();
			FileChannel outChannel = new FileOutputStream(dst).getChannel();
			try {
				inChannel.transferTo(0, inChannel.size(), outChannel);
			} finally {
				if (inChannel != null)
					inChannel.close();
				if (outChannel != null)
					outChannel.close();
			}
		}

	}

//--------------------------- ---------------------------------
	public class ExportDataAsXmlTask extends AsyncTask<String, Void, String> {
		private final ProgressDialog dialog = new ProgressDialog(
				ManageData.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Exporting database as XML...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected String doInBackground(final String... args) {
			SQLiteDatabase ddb;
			ddb = SQLiteDatabase.openDatabase(getApplicationContext().getDatabasePath("DBS").toString(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
			DataXmlExporter dm = new DataXmlExporter(ddb);
			try {
				String dbName = args[0];
				String exportFileName = args[1];
				dm.export(dbName, exportFileName);
			} catch (IOException e) {
				Log.e("CMANAGER", e.getMessage(), e);
				return e.getMessage();
			}
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final String errMsg) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			if (errMsg == null) {
				Toast.makeText(ManageData.this, "Export successful!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ManageData.this, "Export failed - " + errMsg,
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	//////////////////////////////////////////////////////////////////////////////////////////////////
	public class ExportDataAsCSVTask extends AsyncTask<String, Void, String> {
		private final ProgressDialog dialog = new ProgressDialog(
				ManageData.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Exporting database as CSV...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected String doInBackground(final String... args) {
			SQLiteDatabase ddb;
			ddb = SQLiteDatabase.openDatabase(getApplicationContext().getDatabasePath("DBS").toString(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
			File dbFile=getDatabasePath("DBS");
			//importovano
			File exportDir = new File(Environment.getExternalStorageDirectory(), "CostManager");
	        if (!exportDir.exists())
	        {
	            exportDir.mkdirs();
	        }
	        File file = new File(exportDir, "CostManager.csv");
	        try
	        {
	        	//file.delete();
	            file.createNewFile();
	            String sqlExport = "select l.a as recordNo, l.value, l.cost_code as CostCode, whe as [date], t.[name] as CostType, p1.name as ParentType, t.path " 
	            		+" from log l LEFT join cost_type t on l.[cost_code] = t.Code " 
	                    +" LEFT join cost_type p1 on t.parent = p1.code "
	                    +" order by 1 ";
	            
	            CsvWriter csvWrite = new CsvWriter(new FileWriter(file),',');
	            Cursor curCSV=ddb.rawQuery(sqlExport,null);
	            csvWrite.writeRecord(curCSV.getColumnNames(), true);
	            while(curCSV.moveToNext())
	            {
	                String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2),curCSV.getString(3),curCSV.getString(4),curCSV.getString(5),curCSV.getString(6)};
	            /* curCSV.getString(3),curCSV.getString(4)};*/
	                csvWrite.writeRecord(arrStr);
	            }
	            csvWrite.close();
	            curCSV.close();
	            return "true";
	        }
	        catch(SQLException sqlEx)
	        {
	            Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
	            return "false";
	        }
	        catch (IOException e)
	        {
	            Log.e("MainActivity", e.getMessage(), e);
	            return "false";
	        }
		}

		// can use UI thread here
		protected void onPostExecute(final String errMsg) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			if (errMsg == "true") {
				Toast.makeText(ManageData.this, "Export successful!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ManageData.this, "Export failed - " + errMsg,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

}